import Bxios from './bxios'
import { useUserStore } from '@/store/modules/user'
import { useStoreInfoStore } from '@/store/modules/storeInfo'
import { useOrderStoreMap } from '@/store/modules/order'
import { TOKEN_OVERDUE } from './bxios.type'
import { doPostLogout, doSignByUser } from '@/apis/sign'
import storage from '@/utils/storage'
import { GrantType } from '@/apis/sign/type'

type Method = 'get' | 'post' | 'put' | 'delete'

// import { useSettingStore } from '@/store/modules/setting'
const bxios = new Bxios({
  baseUrl: import.meta.env.VITE_BASE_URL,
  header: {
    'Device-Id': uni.getSystemInfoSync().deviceId,
    'Client-Type': 'STORE',
    'Shop-Id': 0,
    // WECHAT_MINI_APP
    // Platform: 'WECHAT_MINI_APP',
    Platform: 'H5',
  },
})
let requests: any[] = []
const whiteList = ['gruul-mall-uaa/login?grant_type=refresh_token']
const notNeedTokenList = [
  'gruul-mall-uaa/uaa/auth/captcha/slider',
  'gruul-mall-uaa/uaa/auth/captcha/sms',
  'gruul-mall-uaa/login?grant_type=sms_code',
  '/gruul-mall-uaa/login?grant_type=password',
]
bxios.interceptors.request.use(
  (config) => {
    console.log(storage.get('isRefreshing'))
    console.log(config)
    // 如果正在刷新中
    if (storage.get('isRefreshing') && !whiteList.includes(config.url)) {
      return new Promise((resolve) => {
        requests.push((token: string) => {
          config.header.Authorization = token
          resolve(config)
        })
      })
    }

    const shopId = useStoreInfoStore().shopStoreInfo?.shopId || 0
    if (shopId) {
      config.header['Shop-Id'] = shopId
    }
    const token = useUserStore().token
    if (token) {
      if (!notNeedTokenList.includes(config.url)) {
        config.header.Authorization = token
      }
    } else {
      delete config.header.Authorization
    }
    return Promise.resolve(config)
  },
  (err) => {
    return Promise.reject(err)
  },
)
bxios.interceptors.response.use(
  async ({ data, config }) => {
    const res = data
    const { code, msg } = res
    const $store = useUserStore()
    if (TOKEN_OVERDUE.includes(code)) {
      doPostLogout()
      const $useOrderStoreMap = useOrderStoreMap()
      const $useStoreInfoStore = useStoreInfoStore()
      $store.REMOVE_TOKEN()
      $useOrderStoreMap.REMOVE_ORDER_MAP()
      $useStoreInfoStore.REMOVE_STORE_INFO()
      uni.reLaunch({ url: '/pages/sign/Index' })
      return Promise.reject(res)
    }
    if (code === 4) {
      // 无感刷新
      if (!storage.get('isRefreshing')) {
        storage.set('isRefreshing', true, 30)
        const refresh_token = storage.get('shop_store')?.refresh_token
        const tel = storage.get('shop_store')?.shopAssistantPhone
        console.log(refresh_token)
        console.log(tel)
        debugger
        try {
          const { data } = await doSignByUser(GrantType.REFRESH_TOKEN, { value: refresh_token })
          const newToken = data?.value as string
          if (!newToken) {
            storage.set('isRefreshing', false, 30)
            $store.REMOVE_TOKEN()
            return Promise.reject('token刷新失败')
          }
          const { refreshToken } = data!
          $store.ADD_TOKEN({ access_token: newToken, refresh_token: refreshToken.value, shopAssistantPhone: tel })

          requests.forEach((cb: (t: string) => any) => {
            cb(newToken)
          })
          requests = []
          storage.set('isRefreshing', false, 30)
          config.header.Authorization = newToken
          // config.method转小写
          const method = config.method.toLowerCase() as Method
          return Promise.resolve(bxios[method](config.url, config.data, config.header))
        } catch (error) {
          storage.set('isRefreshing', false, 30)
          console.log('error', error)
          return Promise.reject(error)
        } finally {
          storage.set('isRefreshing', false, 30)
        }
      }
      return new Promise((resolve) => {
        requests.push((token: string) => {
          config.header.Authorization = token
          // config.method转小写
          const method = config.method.toLowerCase() as Method
          resolve(bxios[method](config.url, config.data, config.header))
        })
      })
    }
    return Promise.resolve(res)
  },
  (err) => {
    uni.showToast({
      icon: 'none',
      title: err || '服务器内部错误',
    })
    return Promise.reject(err)
  },
)
export default bxios
